{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 测试 `PrintAfterAll` 和 `PrintBeforeAll`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from io import StringIO\n",
    "from contextlib import redirect_stdout\n",
    "import tvm\n",
    "from tvm import relax\n",
    "from tvm.ir.instrument import PrintAfterAll, PrintBeforeAll\n",
    "from tvm.script import ir as I\n",
    "from tvm.script import relax as R\n",
    "from tvm.script import tir as T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "@T.prim_func\n",
    "def func(a: T.handle, b: T.handle) -> None:\n",
    "    A = T.match_buffer(a, (128, 128, 128, 128))\n",
    "    B = T.match_buffer(b, (128, 128, 128, 128))\n",
    "    for i, j, k, l in T.grid(128, 128, 128, 128):\n",
    "        with T.block(\"B\"):\n",
    "            vi, vj, vk, vl = T.axis.remap(\"SSSS\", [i, j, k, l])\n",
    "            B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0\n",
    "\n",
    "with redirect_stdout(StringIO()) as sio:\n",
    "    with tvm.transform.PassContext(opt_level=3, instruments=[PrintBeforeAll(), PrintAfterAll()]):\n",
    "        tvm.compile(func)\n",
    "all_passes_output = sio.getvalue()\n",
    "assert \"Before Running Pass:\" in all_passes_output\n",
    "assert \"After Running Pass:\" in all_passes_output\n",
    "assert \"pass name: tir.\" in all_passes_output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "@I.ir_module\n",
    "class Module:\n",
    "    @R.function\n",
    "    def func(x: R.Tensor((16,), \"float32\"), y: R.Tensor((16,), \"float32\")):\n",
    "        z = R.add(x, y)\n",
    "        y = z\n",
    "        return y\n",
    "\n",
    "pipeline = relax.get_pipeline(\"default_build\")\n",
    "with redirect_stdout(StringIO()) as sio:\n",
    "    with tvm.transform.PassContext(opt_level=3, instruments=[PrintBeforeAll(), PrintAfterAll()]):\n",
    "        pipeline(Module)\n",
    "all_passes_output = sio.getvalue()\n",
    "assert \"Before Running Pass:\" in all_passes_output\n",
    "assert \"After Running Pass:\" in all_passes_output\n",
    "assert \"pass name: _pipeline\" in all_passes_output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py313",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
